package com.sanchunhui.psc.ui.activity

import android.content.DialogInterface
import android.content.Intent
import android.graphics.Point
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder
import cn.bingoogolapple.refreshlayout.BGARefreshLayout
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.kennyc.view.MultiStateView
import com.noober.menu.FloatMenu
import com.sanchunhui.psc.R
import com.sanchunhui.psc.common.BaseApplication
import com.sanchunhui.psc.data.protocol.Member
import com.sanchunhui.psc.data.protocol.ResponseInfo
import com.sanchunhui.psc.data.protocol.Team
import com.sanchunhui.psc.ext.startLoading
import com.sanchunhui.psc.injection.component.DaggerProjectTeamComponent
import com.sanchunhui.psc.injection.module.ProjectTeamModule
import com.sanchunhui.psc.presenter.TeamMembersPresenter
import com.sanchunhui.psc.presenter.view.TeamMembersView
import com.sanchunhui.psc.ui.adapter.BaseRecyclerViewAdapter
import com.sanchunhui.psc.ui.adapter.TeamMembersAdapter
import com.sanchunhui.ui.activity.BaseMvpActivity
import kotlinx.android.synthetic.main.activity_team_members.*
import kotlinx.android.synthetic.main.activity_team_members.mMultiStateView
import kotlinx.android.synthetic.main.activity_team_members.mRefreshLayout
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONObject

/**
 * @Author zyx
 * @Date 2021/4/20-15:11
 * @Dscribe 从小组列表点击进去小组成员界面
 */
class TeamMembersActivity : BaseMvpActivity<TeamMembersPresenter>(), TeamMembersView, BGARefreshLayout.BGARefreshLayoutDelegate ,View.OnClickListener {

    private lateinit var mMembersAdapter: TeamMembersAdapter
    private lateinit var mTeam: Team

    private var mCurrentPage: Int = 1
    private var mMaxPage: Int = 1

    private val point = Point()


    private var onlineMemberList :  MutableList<Char> = mutableListOf()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_team_members)

        processIntent()
        initHeader()
        initView()
        initRefreshLayout()
        loadOnlineMember()
    }

    /*
       加载数据
    */
    override fun onStart() {
        super.onStart()
        initTeamInfo()
        loadData()
    }

    private fun initTeamInfo() {
        val user = BaseApplication.mUser
        mPresenter.getProjectTeamInfo(mTeam.id,user.token.toString())
    }

    /*
      初始化视图
   */
    fun initView() {
        mMembersRv.layoutManager = LinearLayoutManager(this)
        mMembersAdapter = TeamMembersAdapter(this)
        mMembersRv.adapter = mMembersAdapter

        mMembersAdapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<Member> {
            override fun onItemClick(item: Member, position: Int) {
               startActivity<MemberDeviceMessageActivity>()
            }
        })

        mMembersAdapter.setOnItemLongClickListener(object :BaseRecyclerViewAdapter.OnItemLongClickLintener<Member>{
            override fun onItemLongClick(item: Member, position: Int) {
                val floatMenu = FloatMenu(this@TeamMembersActivity)
                floatMenu.items("设置为该组负责人", "删除该成员")
                floatMenu.setOnItemClickListener { v, position ->

                    val user = BaseApplication.mUser
                    if (position == 0) { // 设置指定分组负责⼈
                        val message = String.format(this@TeamMembersActivity.getString(R.string.set_team_leader),item.name)
                        AlertDialog.Builder(this@TeamMembersActivity)
                            .setTitle("设置小组负责人")
                            .setMessage(message)
                            .setNegativeButton(R.string.cancel, null)
                            .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener {
                                    dialogInterface, i ->  mPresenter.setTeamLeader(mTeam.id,user.token.toString(),item.id)
                            })
                            .show()

                    } else if (position == 1) { // 移除项⽬（分组）中的成员
                        val message = String.format(this@TeamMembersActivity.getString(R.string.delete_member_message),item.name)
                        AlertDialog.Builder(this@TeamMembersActivity)
                            .setTitle("移除小组成员")
                            .setMessage(message)
                            .setNegativeButton(R.string.cancel, null)
                            .setPositiveButton(R.string.confirm, DialogInterface.OnClickListener {
                                    dialogInterface, i ->  mPresenter.deleteMember(user.token.toString(),item.id)
                            })
                            .show()
                    }
//                    Toast.makeText(
//                        this@TeamMembersActivity,
//                        "菜单$position",
//                        Toast.LENGTH_SHORT
//                    ).show()
                }
                floatMenu.show(point)
            }
        })

        tv_add_member.setOnClickListener(this)
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev!!.getAction() == MotionEvent.ACTION_DOWN) {
            point.x = ev.getRawX().toInt()
            point.y = ev.getRawY().toInt()
        }
        return super.dispatchTouchEvent(ev)
    }

    /*
     初始化刷新视图
  */
    private fun initRefreshLayout() {
        mRefreshLayout.setDelegate(this)
        val viewHolder = BGANormalRefreshViewHolder(this, true)
        viewHolder.setLoadMoreBackgroundColorRes(R.color.common_bg)
        viewHolder.setRefreshViewBackgroundColorRes(R.color.common_bg)
        mRefreshLayout.setRefreshViewHolder(viewHolder)
    }

    private fun initHeader() {
        ib_back.setOnClickListener { finish() }
        tv_add_member.setOnClickListener(this)
    }

    private fun processIntent() {
        if (intent.hasExtra("teamInfo")) {
            mTeam = intent.getSerializableExtra("teamInfo") as Team
            tv_team_title.text = mTeam.name.toString()+"(0/${mTeam.member_cnt})"
        }
    }

    private fun loadOnlineMember() {
        val user = BaseApplication.mUser
        mPresenter.getOnlineMember(mTeam.id, user.token.toString())
    }

    /*
      Dagger注册
   */
    override fun injectComponent() {
        DaggerProjectTeamComponent.builder().activityComponent(mActivityComponent).projectTeamModule(ProjectTeamModule()).build().inject(this)
        mPresenter.mView = this
    }

    /*
       加载数据
    */
    private fun loadData() {
        val user = BaseApplication.mUser
        mMultiStateView.startLoading()
        mPresenter.getTeamMember(mTeam.id,user.token.toString())
    }

    override fun onGetProjectTeamInfoResult(result: ResponseInfo) {
        if (result.code == 0) {
            mTeam = Gson().fromJson(result.data.toString(), Team::class.java) as Team
            mMembersAdapter.leadeMemberId = mTeam.leader_member_id
            mMembersAdapter.notifyDataSetChanged()
//            headerTitle.text = mTeam.name+"(0/${mTeam.member_cnt})"
        }
    }

    /*
        设置组长
     */
    override fun onSetTeamLeaderResult(result: Boolean) {
        toast("设置成功")
        initTeamInfo()
    }

    /*
        移除成员
     */
    override fun onDeleteMemberResult(result: Boolean) {
        toast("移除成员成功")
        loadData()
    }

    // 获取在线成员结果
    override fun onGetOnlineMemberResult(result: MutableList<Char>) {
        onlineMemberList = result
    }

    // 获取小组成员结果
    override fun onGetTeamMemberResult(result: ResponseInfo) {
        mRefreshLayout.endLoadingMore()
        mRefreshLayout.endRefreshing()
        if (result.code == 0) {
            val json = result.data
            parserJson(json.toString())
        } else if (result.code == 401) {
            startActivity<LoginActivity>()
        }
    }

    /*
       解析数据
   */
    fun parserJson(json: String) {
        val gson = Gson()
        var jsonObject = JSONObject(json)
        var members = jsonObject.getString("members")
        var memberList : ArrayList<Member> = gson.fromJson(members, object : TypeToken<List<Member>>() {}.type)

        if (memberList.isNotEmpty()) {
            mMembersAdapter.leadeMemberId = mTeam.leader_member_id
            mMembersAdapter.setData(memberList)
            mMultiStateView.viewState = MultiStateView.ViewState.CONTENT
        } else {
            mMultiStateView.viewState = MultiStateView.ViewState.EMPTY
        }
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.tv_add_member -> {
                val intent : Intent = Intent(this, SearchMemberActivity::class.java)
                intent.putExtra("intentStr", "2")
                intent.putExtra("teamIdStr", mTeam.id.toString())
                startActivity(intent)
            }
        }
    }

    override fun onBGARefreshLayoutBeginLoadingMore(refreshLayout: BGARefreshLayout?): Boolean {
        return if (mCurrentPage < mMaxPage) {
            mCurrentPage++
            loadData()
            true
        } else {
            false
        }
    }

    override fun onBGARefreshLayoutBeginRefreshing(refreshLayout: BGARefreshLayout?) {
        mCurrentPage = 1
        loadData()
    }

}